﻿var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var signCode = "slel3@lsl334xx,deka";
var Cio = require('socket.io-client');
var log = require("./../util/loginfo").getInstand;
var gameInfo = require('./class/game').getInstand;
var gameConfig = require('./config/gameConfig');

var Csocket = Cio('http://localhost:13000');

Csocket.on('disconnect', function (data) {
    log.info("登录服务器被断开")
});

Csocket.on('connected', function (msg) {
    log.info("与登录服务器进行连接......");
    var info = {
        serverName: "拉霸游戏_" + (gameConfig.gameId) + "_" + gameConfig.gameName,
        serverId: gameConfig.serverId,
        signCode: "slel3@lsl334xx,deka"
    };
    Csocket.emit('GameServerConnect', info);
});

Csocket.on('GameServerConnectResult', function (msg) {
    if (msg.resultCode) {
        log.info("连接成功");
    }
});

Csocket.on('LoginGameResult', function (msg) {
    try {
        if (!msg) {
            return;
        }
        log.info(".登录" + gameConfig.gameName + "服务器回应" + JSON.stringify(msg));
        if (msg.ResultCode) {
            gameInfo.updateUser(msg.userInfo);
        } else {
            gameInfo.deleteUserById(msg.userid, msg.msg);
        }
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('addgold', function (msg) {
    try {
        if (!msg) {
            return;
        }
        //log.info(msg);
        var result = gameInfo.addgold(msg.userid, msg.addgold);
        Csocket.emit('addgoldResult', {Result: result});
    
        //当前用户桌子广播
        var User = gameInfo.getUser(msg.userid);
        if (User) {
            var tablestring = "table" + User.getTable();
            io.sockets.in(tablestring).emit('userGoldUpdate', {userId: msg.userid, updateSocre: User.getScore()});
        }
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('getgold', function (msg) {
    try {
        if (!msg) {
            return;
        }
    
        var score = gameInfo.getPlayerScore(msg.userid);
        Csocket.emit('getgoldResult', {Result: 1, score: score});
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('disconnectUser', function (msg) {
    try {
        var list = gameInfo.getOnlinePlayer();
        if (list[msg.userId]) {
            // kicked, ZZZ-20230509
            list[msg.userId]._socket.emit(msg.sysCommand, msg);
            list[msg.userId]._socket.disconnect();
        } else {
            log.info("用户不存在");
            var result = {ResultCode: 0, userId: msg.userId};
            Csocket.emit("userDisconnect", result);
        }
    } catch (error) {
        log.err(error);
    }
});


Csocket.on('applyMatchResult', function (_info) {
    try {
        //log.info(_info);
        gameInfo.addRankUserList(_info);
        //gameInfo.fishShoot(socket,fishShootInfo);
    } catch (error) {
        log.err(error);
    }
});


Csocket.on('Setmaintain', function () {
    try {
        gameInfo.Setmaintain();
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('updateGamblingGame', function (_info) {
    try {
        let data = JSON.parse(_info);
        _info = data;
    } catch (e) {
        log.warn('LoginGame-json');
    }
    try {
        gameInfo.updateGamblingBalanceGold(_info);
    } catch (error) {
        log.err(error);
    }
});

gameInfo.setIo(io, Csocket);

io.on('connection', function (socket) {

    //log.info(socket + 'connected');
    socket.emit('connected', 'connect game server');


    //客户登录游戏
    socket.on('LoginGame', function (GameInfo) {
        try {
            var data = JSON.parse(GameInfo);
            GameInfo = data;
        } catch (e) {
            log.warn('LoginGame-json');
        }
        log.info("login game ", data);

        try {
            if (!GameInfo || !GameInfo.sign) {
                log.info("登录游戏,参数不正确!");
                return;
            }
    
            if (!gameInfo.getUser(GameInfo.userid)) {
                gameInfo.addUser(GameInfo, socket);
                var msg = {
                    userid: GameInfo.userid,
                    sign: GameInfo.sign,
                    gameId: gameInfo.serverId,
                    serverSign: signCode,
                    serverId: gameConfig.serverId
                };
                Csocket.emit('LoginGame', msg);
                //log.info("test4.发送新用户登录完成,让登录服务器删除用户")
            } else {
                log.info("用户已经在服务器了，无需重复登录");
            }
        } catch (error) {
            log.err(error);
        }
    });

    //然后再登录房间
    socket.on('LoginRoom', function (RoomInfo) {
        try {
            var data = JSON.parse(RoomInfo);
            RoomInfo = data;
        } catch (e) {
            log.warn('LoginRoom-json');
        }
        try {
            //如果没有房间概念，就默认为1
            //这还应该检测是否进入了游戏，如果没有需要先进入
            //log.info("进入房间")
            gameInfo.LoginRoom(socket.userId, RoomInfo.roomid, socket); 
        } catch (error) {
            log.err(error);
        }
    });

    //离开房间
    socket.on('LogoutRoom', function () {
        try {
            gameInfo.LogoutRoom(socket);
        } catch (error) {
            log.err(error);
        }
    });


    //登录游戏获取免费游戏次数
    socket.on('LoginfreeCount', function () {
        try {
            gameInfo.LoginfreeCount(socket.userId, socket);
        } catch (error) {
            log.err(error);
        }
    });

    //下注
    socket.on('lottery', function (lottery) {
        log.info("下注 " + lottery);
        try {
            var data = JSON.parse(lottery);
            lottery = data;
        } catch (e) {
            //log.warn('lottery-json');
        }

        try {
            var result = gameInfo.lottery(socket.userId, lottery.bet);
            if (result.code < 1) {
                socket.emit('lotteryResult', {ResultCode: result.code});
            } else {
                socket.emit('lotteryResult', {
                    ResultCode: result.code,
                    ResultData: {
                        userscore: result.userscore,
                        winscore: result.winscore,
                        viewarray: result.viewarray,
                        winfreeCount: result.winfreeCount,
                        freeCount: result.freeCount,
                        score_pool: result.score_pool
                    }
                });
            }
        } catch (error) {
            log.err(error);
        }
    });

    //离线操作
    socket.on('disconnect', function () {
        try {
            if (!socket.userId) {
                return;
            }
            //通知登录服务器，已经下线存储游戏数据
            var userInfo = gameInfo.getUser(socket.userId);
            if (!userInfo) {
                log.info("用户未登录离开!");
                return;
            }
    
            if (!userInfo.Islogin()) {
                userInfo._isLeave = true;
                log.warn('未更新用户数据离开');
                return;
            }
    
            gameInfo.deleteUser(socket);
            var result = {
                ResultCode: 1,
                userId: userInfo._userId,
                userScore: userInfo._score,
                gameId: gameConfig.serverId,
                nolog: true
            };
            Csocket.emit("userDisconnect", result);
            //断线存储相应数据(在新的数据库里存储,消耗子弹与收获金币)
            socket.userId = null;
        } catch (error) {
            log.err(error);
        }
    });
});


app.set('port', process.env.PORT || gameConfig.port);

var server = http.listen(app.get('port'), function () {
    log.info('start at port:' + server.address().port);
});

log.info("拉霸_" + gameConfig.gameId + "_" + gameConfig.gameName + "服务器启动");

